﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.IO;
using System.Xml.Serialization;

using ecdl.demo.resources;

namespace ecdl.demo.model.precondition {
    //normally this should be an interface but the xml-serialization 
    //is easier using an abstract class as base
    public abstract class Precondition {
        public abstract void Execute(string rootPath);
    }

    public class CreateDirectory : Precondition {
        [XmlAttribute("fullPath")]
        public string FullPath { get; set; }

        public CreateDirectory() {

        }

        public CreateDirectory(string fullPath) {
            this.FullPath = fullPath;
        }

        public override void Execute(string rootPath) {
            Directory.CreateDirectory(Path.Combine(rootPath, FullPath));
        }
    }

    public class CreateFile : Precondition {
        private static readonly int ONE_KB = 1024;

        public CreateFile() {

        }

        [XmlAttribute("fullPath")]
        public string FullPath { get; set; }

        public CreateFile(string fullPath) {
            this.FullPath = fullPath;
        }

        [XmlAttribute("useResource")]
        public string UseResource { get; set; }

        public override void Execute(string rootPath) {
            string destinationFile = Path.Combine(rootPath, FullPath);

            if (UseResource != null && UseResource.Length > 0) {
                string source = EcdlResources.GetResourceUri(UseResource);
                File.Copy(source, destinationFile);
            } else {
                CreateOneKbFile(destinationFile);
            }
        }

        private static void CreateOneKbFile(string destinationFile) {
            FileStream file = null;
            try {
                file = File.Create(destinationFile);
                file.Write(new byte[ONE_KB], 0, ONE_KB);
            } finally {
                if (file != null)
                    file.Close();
            }
        }
    }
}
